﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class ImportScopeRule : ILRule<ImportScopeHandle>
    {
        [ILInfo(true, ILInfoParseMethod.AsEntityHandle)]
        public ImportScopeHandle ParentScope { get; }

        public byte[] Imports { get; }

        public ImportDefinitionCollection ImportDefinitions { get; }

        public ImportScopeRule(
            ImportScopeHandle parentScope,
            byte[] imports)
            : base()
        {
            ParentScope = parentScope;
            Imports = imports;
        }

        public ImportScopeRule(MetadataReader reader, ImportScopeHandle importScopeHandle)
            : base(reader)
        {
            ImportScope importScope = reader.GetImportScope(importScopeHandle);
            ParentScope = importScope.Parent;
            Imports = reader.GetBlobBytes(importScope.ImportsBlob);
            ImportDefinitions = importScope.GetImports();
        }

        public override ImportScopeHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddImportScope(
                parentScope: ParentScope,
                imports: Imports == null ? default : builder.GetOrAddBlob(Imports));
        }
    }
}